﻿Imports System.Text
Imports System.IO
Imports System.Runtime.InteropServices
Imports EnvDTE
Imports Microsoft.VisualStudio.OLE.Interop
Imports Microsoft.VisualStudio.Shell
Imports Microsoft.VisualStudio.Text
Imports Microsoft.VisualStudio.TextManager.Interop
Imports Microsoft.VisualStudio.Text.Editor

Namespace Microsoft.VisualStudio.IntellisensePresenter
	''' <summary>
	''' Provides helper functionality for Visual Studio
	''' </summary>
    Friend Class VisualStudioHelper

        Friend Property ServiceProvider As System.IServiceProvider

        Friend Sub New(ByVal view As ITextView)
            Me.New(view.TextBuffer)
        End Sub

        Friend Sub New(ByVal textBuffer As ITextBuffer)
            Me.ServiceProvider = GetServiceProviderFromTextBuffer(textBuffer)
        End Sub

        <System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000")>
        Private Shared Function GetServiceProviderFromTextBuffer(ByVal textBuffer As ITextBuffer) As System.IServiceProvider
            If textBuffer.Properties.ContainsProperty(GetType(IVsTextBuffer)) Then
                Dim objectWithSite = textBuffer.Properties.GetProperty(Of IObjectWithSite)(GetType(IVsTextBuffer))
                If objectWithSite IsNot Nothing Then
                    Dim serviceProviderGuid = GetType(Microsoft.VisualStudio.OLE.Interop.IServiceProvider).GUID
                    Dim ppServiceProvider = IntPtr.Zero
                    ' Get the service provider pointer using the Guid of the OleInterop ServiceProvider
                    objectWithSite.GetSite(serviceProviderGuid, ppServiceProvider)

                    If ppServiceProvider <> IntPtr.Zero Then
                        ' Create a System.ServiceProvider with the OleInterop ServiceProvider
                        Return New ServiceProvider(CType(Marshal.GetObjectForIUnknown(ppServiceProvider), OLE.Interop.IServiceProvider))
                    End If
                End If
            End If

            Return Nothing
        End Function

        Friend Sub Navigate(ByVal uri As String)
            If Not String.IsNullOrEmpty(uri) Then
                If Me.ServiceProvider IsNot Nothing Then
                    Dim vs = TryCast(Me.ServiceProvider.GetService(GetType(DTE)), DTE)
                    If vs IsNot Nothing Then
                        vs.ItemOperations.Navigate(uri, vsNavigateOptions.vsNavigateOptionsDefault)
                    End If
                End If
            End If

        End Sub
    End Class
End Namespace